<template>
  <a-drawer
    v-model:visible="visible"
    title="导入设备资源"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'"
    ok-text="确认导入"
    cancel-text="取消导入"
    @before-ok="save"
    @close="reset"
  >
    <a-form ref="formRef" :model="form" size="large" auto-label-width>
      <a-alert style="margin-bottom: 15px">
        请按照模板要求填写数据，填写完毕后，请先上传并进行解析。
        <template #action>
          <a-link @click="downloadTemplate">
            <template #icon><GiSvgIcon name="file-excel" :size="16" /></template>
            <template #default>下载模板</template>
          </a-link>
        </template>
      </a-alert>
      <fieldset>
        <legend>1.解析数据</legend>
        <div class="file-box">
          <a-upload
            draggable
            :custom-request="handleUpload"
            :limit="1"
            :show-retry-button="false"
            :show-cancel-button="false"
            tip="仅支持xls、xlsx格式"
            :file-list="uploadFile"
            accept=".xls, .xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          />
        </div>
        <div v-if="dataResult.importKey" class="file-box">
          <a-space size="large">
            <a-statistic title="总计行数" :value="dataResult.totalRows" />
            <a-statistic title="有效行数" :value="dataResult.validRows" />
          </a-space>
          <a-alert v-if="dataResult.validRows < dataResult.totalRows" type="warning" style="margin-top: 10px">
            检测到{{ dataResult.totalRows - dataResult.validRows }}行无效数据（已自动过滤）
          </a-alert>
        </div>
      </fieldset>
    </a-form>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { type FormInstance, Message, type RequestOption } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { 
  downloadDeviceStoreImportTemplate, 
  importDeviceStore, 
  parseImportDeviceStore 
} from '@/apis/generator/deviceStore'
import { useDownload, useResetReactive } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const visible = ref(false)
const formRef = ref<FormInstance>()
const uploadFile = ref([])

// 修正：添加 importKey 属性
const [form, resetForm] = useResetReactive({
  defaultStatus: 1,
  importKey: ''
})

const dataResult = ref({
  importKey: '',
  totalRows: 0,
  validRows: 0,
})

// 重置表单
const reset = () => {
  formRef.value?.resetFields()
  dataResult.value = {
    importKey: '',
    totalRows: 0,
    validRows: 0
  }
  uploadFile.value = []
  resetForm()
}

// 下载模板
const downloadTemplate = () => {
  useDownload(() => downloadDeviceStoreImportTemplate())
}

// 上传解析导入数据
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController();
  (async function requestWrap() {
    const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
    onProgress(20)
    const formData = new FormData()
    formData.append(name as string, fileItem.file as Blob)
    try {
      const res = await parseImportDeviceStore(formData)
      dataResult.value = res.data
      Message.success(`解析成功，共 ${res.data.totalRows} 行数据，其中 ${res.data.validRows} 行有效`)
      onSuccess(res)
    } catch (error) {
      Message.error('文件解析失败，请检查文件格式和内容')
      onError(error)
    }
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}

// 执行导入
const save = async () => {
  try {
    if (!dataResult.value.importKey) {
      Message.warning('请先上传文件，解析导入数据')
      return false
    }
    if (dataResult.value.validRows === 0) {
      Message.warning('没有有效的可导入数据')
      return false
    }
    
    form.importKey = dataResult.value.importKey
    const res = await importDeviceStore(form)
    Message.success(`导入成功! 共导入 ${res.data.insertRows} 条数据`)
    emit('save-success')
    return true
  } catch (error) {
    Message.error('导入失败，请稍后重试')
    return false
  }
}

// 打开抽屉
const onOpen = () => {
  reset()
  visible.value = true
}

defineExpose({ onOpen })
</script>

<style scoped lang="scss">
fieldset {
  padding: 15px 15px 0 15px;
  margin-bottom: 15px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

fieldset legend {
  color: rgb(var(--gray-10));
  padding: 2px 5px 2px 5px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

.file-box {
  margin-bottom: 20px;
  margin-left: 10px;
}
</style>